<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const router = useRouter();

// 环境监控设备数据
const environmentDevices = ref([
  {
    id: '1',
    name: '温湿度传感器-101',
    deviceId: 'ENV001',
    status: 'online',
    location: '1号楼101房间',
    lastUpdate: '2024-01-19 15:30:00',
    temperature: 24.5,
    humidity: 65,
    airQuality: 85,
    co2: 450,
    pm25: 12,
    battery: 92,
    signal: 88,
  },
  {
    id: '2',
    name: '空气质量监测器-大厅',
    deviceId: 'ENV002',
    status: 'online',
    location: '1号楼大厅',
    lastUpdate: '2024-01-19 15:30:00',
    temperature: 23.8,
    humidity: 58,
    airQuality: 78,
    co2: 520,
    pm25: 18,
    battery: 85,
    signal: 92,
  },
  {
    id: '3',
    name: '环境监测器-餐厅',
    deviceId: 'ENV003',
    status: 'warning',
    location: '1号楼餐厅',
    lastUpdate: '2024-01-19 15:25:00',
    temperature: 26.2,
    humidity: 72,
    airQuality: 65,
    co2: 680,
    pm25: 25,
    battery: 45,
    signal: 75,
  },
]);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  location: '',
  airQuality: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors = {
    online: 'green',
    offline: 'red',
    warning: 'orange',
    error: 'red',
  };
  return colors[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    warning: '异常',
    error: '故障',
  };
  return texts[status] || status;
};

// 获取温度颜色
const getTemperatureColor = (temp: number) => {
  return temp > 28 ? 'red' : temp > 25 ? 'orange' : 'green';
  temp28;
};

// 获取湿度颜色
const getHumidityColor = (humidity: number) => {
  return humidity > 80 ? 'red' : humidity > 70 ? 'orange' : 'green';
  humidity80;
};

// 获取空气质量颜色
const getAirQualityColor = (quality: number) => {
  return quality >= 80 ? 'green' : quality >= 60 ? 'orange' : 'red';
  quality80;
};

// 获取CO2颜色
const getCO2Color = (co2: number) => {
  return co2 > 800 ? 'red' : co2 > 600 ? 'orange' : 'green';
  co2800;
};

// 获取PM2.5颜色
const getPM25Color = (pm25: number) => {
  return pm25 > 35 ? 'red' : pm25 > 25 ? 'orange' : 'green';
  pm2535;
};

// 获取电池颜色
const getBatteryColor = (battery: number) => {
  return battery > 60 ? 'green' : battery > 30 ? 'orange' : 'red';
  battery60;
};

// 表格列定义
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '安装位置',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '温度',
    dataIndex: 'temperature',
    key: 'temperature',
    width: 100,
  },
  {
    title: '湿度',
    dataIndex: 'humidity',
    key: 'humidity',
    width: 100,
  },
  {
    title: '空气质量',
    dataIndex: 'airQuality',
    key: 'airQuality',
    width: 120,
  },
  {
    title: 'CO₂',
    dataIndex: 'co2',
    key: 'co2',
    width: 100,
  },
  {
    title: 'PM2.5',
    dataIndex: 'pm25',
    key: 'pm25',
    width: 100,
  },
  {
    title: '电池电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 过滤后的数据
const filteredDevices = computed(() => {
  let result = environmentDevices.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  if (searchForm.airQuality) {
    switch (searchForm.airQuality) {
      case 'good': {
        result = result.filter((item) => item.airQuality >= 80);
        break;
      }
      case 'moderate': {
        result = result.filter(
          (item) => item.airQuality >= 60 && item.airQuality < 80,
        );
        break;
      }
      case 'poor': {
        result = result.filter((item) => item.airQuality < 60);
        break;
      }
    }
  }

  return result;
});

// 环境监控统计
const environmentStatistics = computed(() => {
  const total = environmentDevices.value.length;
  const online = environmentDevices.value.filter(
    (d) => d.status === 'online',
  ).length;
  const warning = environmentDevices.value.filter(
    (d) => d.status === 'warning',
  ).length;
  const offline = environmentDevices.value.filter(
    (d) => d.status === 'offline',
  ).length;

  // 计算平均指标
  const avgTemperature =
    environmentDevices.value.reduce((sum, d) => sum + d.temperature, 0) / total;
  const avgHumidity =
    environmentDevices.value.reduce((sum, d) => sum + d.humidity, 0) / total;
  const avgAirQuality =
    environmentDevices.value.reduce((sum, d) => sum + d.airQuality, 0) / total;

  return {
    total,
    online,
    warning,
    offline,
    avgTemperature,
    avgHumidity,
    avgAirQuality,
  };
});

// 查看设备详情
const viewDevice = (record: any) => {
  router.push(`/hotel/iot-devices/detail/${record.id}`);
};

// 控制设备
const controlDevice = (record: any) => {
  Modal.info({
    title: `设备控制 - ${record.name}`,
    width: 800,
    content: '设备控制功能开发中...',
  });
};

// 查看历史数据
const viewHistory = (record: any) => {
  Modal.info({
    title: `历史数据 - ${record.name}`,
    width: 800,
    content: '设备历史数据查看功能开发中...',
  });
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: '',
    location: '',
    airQuality: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

onMounted(() => {
  pagination.total = filteredDevices.value.length;
});
</script>

<template>
  <div class="environment-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>环境监控</h2>
      <Space>
        <Button @click="router.push('/hotel/iot-devices')">
          <IconifyIcon icon="ant-design:arrow-left-outlined" />
          返回设备列表
        </Button>
        <Button type="primary">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加设备
        </Button>
      </Space>
    </div>

    <!-- 统计信息 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number total">
              {{ environmentStatistics.total }}
            </div>
            <div class="stat-label">设备总数</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number online">
              {{ environmentStatistics.online }}
            </div>
            <div class="stat-label">在线设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number warning">
              {{ environmentStatistics.warning }}
            </div>
            <div class="stat-label">异常设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{ environmentStatistics.avgTemperature.toFixed(1) }}°C
            </div>
            <div class="stat-label">平均温度</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{ environmentStatistics.avgHumidity.toFixed(1) }}%
            </div>
            <div class="stat-label">平均湿度</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{ environmentStatistics.avgAirQuality.toFixed(0) }}
            </div>
            <div class="stat-label">平均空气质量</div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <Form.Item label="设备名称">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入设备名称"
            allow-clear
          />
        </Form.Item>
        <Form.Item label="设备状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="online">在线</Select.Option>
            <Select.Option value="offline">离线</Select.Option>
            <Select.Option value="warning">异常</Select.Option>
            <Select.Option value="error">故障</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="安装位置">
          <Input
            v-model:value="searchForm.location"
            placeholder="请输入安装位置"
            allow-clear
          />
        </Form.Item>
        <Form.Item label="空气质量">
          <Select
            v-model:value="searchForm.airQuality"
            placeholder="请选择等级"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="good">良好</Select.Option>
            <Select.Option value="moderate">一般</Select.Option>
            <Select.Option value="poor">较差</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <!-- 设备列表 -->
    <Card title="环境监控设备列表" class="list-card">
      <Table
        :columns="columns"
        :data-source="filteredDevices"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'temperature'">
            <Tag :color="getTemperatureColor(record.temperature)">
              {{ record.temperature }}°C
            </Tag>
          </template>
          <template v-else-if="column.key === 'humidity'">
            <Tag :color="getHumidityColor(record.humidity)">
              {{ record.humidity }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'airQuality'">
            <Tag :color="getAirQualityColor(record.airQuality)">
              {{ record.airQuality }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'co2'">
            <Tag :color="getCO2Color(record.co2)"> {{ record.co2 }}ppm </Tag>
          </template>
          <template v-else-if="column.key === 'pm25'">
            <Tag :color="getPM25Color(record.pm25)">
              {{ record.pm25 }}μg/m³
            </Tag>
          </template>
          <template v-else-if="column.key === 'battery'">
            <Tag :color="getBatteryColor(record.battery)">
              {{ record.battery }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDevice(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="controlDevice(record)">
                控制
              </Button>
              <Button type="link" size="small" @click="viewHistory(record)">
                历史
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.environment-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 16px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.total {
  color: #1890ff;
}

.stat-number.online {
  color: #52c41a;
}

.stat-number.warning {
  color: #faad14;
}

.stat-number.offline {
  color: #f5222d;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  background: white;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
